# -*- coding: utf-8 -*-
# minecraft_custom_script.py
# Author: YourName
# 描述：自定义Minecraft服务器脚本（网易版/BDS Python API）

import _serverlevel  # 网易/BDS提供的底层API
import json
import time

# ===== 1. 初始化部分 ===== #
def init_script():
    """服务器启动时自动执行"""
    print("[脚本加载] 自定义脚本已加载！")


# ===== 2. 基础API封装（参考serverlevel.py） ===== #
def create_mob(mob_type, pos, dimension=0):
    """生成一只生物"""
    entity_id = _serverlevel.create_entity(
        mob_type, 
        pos, 
        (0, 0),  # 初始旋转角度
        None,    # player_id (可选)
        dimension
    )
    if entity_id:
        print(f"[脚本] 已生成 {mob_type}，ID: {entity_id}")
    return entity_id


def set_block_safe(block_id, pos, player_id=None):
    """安全设置方块（避免崩溃）"""
    try:
        success = _serverlevel.set_block(block_id, 0, pos, player_id)
        if success:
            print(f"[脚本] 方块 {block_id} 已放置在 {pos}")
        return success
    except Exception as e:
        print(f"[错误] 设置方块失败: {e}")
        return False


# ===== 3. 游戏逻辑（事件监听） ===== #
def on_player_join(event):
    """玩家加入服务器事件"""
    player_id = event["player_id"]
    player_name = _serverlevel.get_display_name(player_id)
    
    # 欢迎消息 + 给予初始物品
    _serverlevel.notify_msg("§a欢迎 §e" + player_name + " §a加入游戏！")
    _serverlevel.give_item(player_id, "minecraft:diamond_sword", 1)


def on_block_break(event):
    """玩家破坏方块事件"""
    player_id = event["player_id"]
    pos = event["position"]
    
    # 禁止破坏基岩
    block_id, _ = _serverlevel.get_block_and_data(pos[0], pos[1], pos[2])
    if block_id == "minecraft:bedrock":
        _serverlevel.notify_one_msg(player_id, "§c你不能破坏基岩！")
        return False  # 取消事件


# ==== 4. 注册事件 ==== #
def register_events():
    """注册服务器事件监听"""
    import common.system.eventHandler as event

    # 玩家加入事件
    event.register_event_handler(
        "minecraft:player_join_event", 
        on_player_join
    )

    # 方块破坏事件
    event.register_event_handler(
        "minecraft:block_break_event",
        on_block_break
    )


# ==== 5. 主入口 ==== #
if __name__ == "__main__":
    init_script()
    register_events()
    print("[脚本] 事件监听已启动！")
